package com.light.mytext.mycustomview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import com.light.mytext.R

class LineView(context: Context?, width: Int) :
    View(context), View.OnTouchListener {
    var mStartX = 0f
    var mStartY = 5f
    var mEndX = width - mStartX * 2
    var mEndY = 5f
    var mPaint: Paint? = null
    var viewWidth = (width-mStartX * 2).toInt()
    var viewHeight=100

    var lineHeight = 5
    var aViewWidth = width - 60
    var aViewHeight = 20
    var moveX = 0
    var moveY = 0
    var downRawX = 0
    var downRawY = 0

    var screenWidth = 0
    var screenHeight = 0
    var offsetX = 0
    var offsetY = 0
    var bianDistance=10

    var direction="Center"

    init {
        initPaint()
    }

    fun initPaint() {
        mPaint = Paint()
        mPaint!!.isAntiAlias = true//设置画笔抗锯齿
        mPaint!!.style = Paint.Style.STROKE//设置画笔样式
        mPaint!!.color = Color.WHITE
        mPaint!!.strokeWidth = 5f
        setOnTouchListener(this)
        initScreenW_H()
    }

    /**
     * 初始化获取屏幕宽高
     */
    protected fun initScreenW_H() {
        screenHeight = resources.displayMetrics.heightPixels
        screenWidth = resources.displayMetrics.widthPixels
    }

    override fun draw(canvas: Canvas?) {
        super.draw(canvas)
        /*val pathG = Path()
        pathG.moveTo(mStartX, mStartY)//起点  左上角
        pathG.lineTo(mStartX + lineWidth, mStartY)//右上角
        pathG.lineTo(mStartX + lineWidth, mStartY + 5)//右下角
        pathG.lineTo(mStartX, mStartY + 5)//左下角
        pathG.close() // 使这些点构成封闭的多边形
        canvas!!.drawPath(pathG, mPaint!!)*/
//        setViewMess()
        canvas!!.drawLine(mStartX, mStartY, mEndX, mEndY, mPaint!!)
        Log.i(
            "LineView==",
            "mStartX==" + mStartX + "mStartY==" + mStartY + "mEndX==" + mEndX + "mEndY==" + mEndY
        )
    }
    /**
     * 设置View相关参数
     */
    fun setViewMess(){
        mStartX=left.toFloat()
        mStartY=top.toFloat()+lineHeight
        mEndX=right.toFloat()
        mEndY=top.toFloat()+lineHeight
    }

    /**
     * 取消选中
     */
    fun cancelChoose() {
        //重置选中paint
        mPaint!!.reset()
        //把画笔颜色设置为透明，重绘
        mPaint!!.color = Color.WHITE
        mPaint!!.isAntiAlias = true//设置画笔抗锯齿
        mPaint!!.style = Paint.Style.STROKE//设置画笔样式
        mPaint!!.strokeWidth = 2f
        invalidate()
    }

    /**
     * 选中
     */
    fun Choose() {
        //重置选中paint
        mPaint!!.reset()
        //把画笔颜色设置为透明，重绘
        mPaint!!.color = resources.getColor(R.color.tv_color_00)
        mPaint!!.isAntiAlias = true//设置画笔抗锯齿
        mPaint!!.style = Paint.Style.STROKE//设置画笔样式
        mPaint!!.strokeWidth = 2f
        invalidate()
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        if (event!!.action == MotionEvent.ACTION_DOWN) {
            downRawX = event!!.rawX.toInt()
            downRawY = event.rawY.toInt()
            moveX = event.x.toInt()
            moveY = event.y.toInt()
            direction=getDirection(downRawX)
            Choose()
        }
        handleEvent(event, v!!)
        invalidate()
        return true
    }

    /**
     * 获取触摸位置
     */
    fun getDirection(dx: Int): String {
        if (dx in 0..(viewWidth * 0.3).toInt()) {
            return "Left"
        }
        if (dx in (viewWidth * 0.7).toInt()..viewWidth) {
            return "Right"
        }
        return "Center"

    }

    /**
     * 处理事件
     */
    fun handleEvent(event: MotionEvent?, v: View) {
        when (event!!.action) {
            MotionEvent.ACTION_MOVE -> {
                //计算移动的距离
                offsetX = event.x.toInt() - moveX
                offsetY = event.y.toInt() - moveY
                val dx: Int = event.rawX.toInt() - downRawX
                val dy: Int = event.rawY.toInt() - downRawY
                Log.i(
                    "LineView==",
                    "getDirection==" + getDirection(event!!.x.toInt())
                )
                when (direction) {
                    "Center" -> {
                        Center_Draw(v)
                    }
                    "Left" -> {
                        mStartX +=dx
                        mStartY+=dy
                    }
                    "Right" -> {
                        mEndX  +=dx
                        mEndY+=dy
                    }
                }
                //记得在这里要重置数据  忘记的话重绘时候会一直闪烁
                downRawX = event.rawX.toInt()
                downRawY = event.rawY.toInt()
                if (direction != "Center" ) {
                    v!!.layout(
                        if (mStartX < mEndX) mStartX.toInt() else mEndX.toInt(),
                        if (mStartY < mEndY) mStartY.toInt() else mEndY.toInt(),
                        if (mStartX < mEndX) mEndX.toInt() else mStartX.toInt(),
                        if (mStartY < mEndY) mEndY.toInt() else mStartY.toInt()
                    )
                    val params: FrameLayout.LayoutParams = layoutParams as FrameLayout.LayoutParams
                    params.leftMargin = if (mStartX < mEndX) mStartX.toInt() else mEndX.toInt()
                    params.topMargin = if (mStartY < mEndY) mStartY.toInt() else mEndY.toInt()
                    layoutParams = params
                }
                Log.i(
                    "LineView==",
                    "mStartX==" + mStartX + "mStartY==" + mStartY + "mEndX==" + mEndX + "mEndY==" + mEndY
                )
                Log.i(
                    "LineView==",
                    "l==" +  (if (mStartX < mEndX) mStartX.toInt() else mEndX.toInt()) + "t==" + (if (mStartY < mEndY) mStartY.toInt() else mEndY.toInt())
                            + "r==" + (if (mStartX < mEndX) mEndX.toInt() else mStartX.toInt()) + "b==" + (if (mStartY < mEndY) mEndY.toInt() else mStartY.toInt())
                )
            }
            MotionEvent.ACTION_UP->{
                cancelChoose()
            }
        }
    }
    fun Center_Draw(v:View){
        var l = v!!.left + offsetX
        var r = l + aViewWidth
        var t = v!!.top + offsetY
        var b = t + aViewHeight

//                Log.i("LineView==","moveX=="+moveX+"moveY=="+moveY+"offsetX=="+offsetX+"offsetY=="+offsetX)
        Choose()
        //调用layout方法来重新放置它的位置
        //划出左边边界
        if (l < 0) {
            l =0
            r = l + aViewWidth
        }
        //划出右边边界
        if (r > screenWidth ) {
            r = screenWidth
            l = r - aViewWidth
        }
        //划出上边边界
        if (t < 0) {
            t = 0
            b = t + aViewHeight
        }
        //划出下边边界
        if (b > screenHeight) {
            b = screenHeight
            t = b - aViewHeight
        }
        v.layout(l, t, r, b)
        /**
         * 由于使用addview()添加控件后，移动控件位置，位置信息并没有更新到layoutParams中 ，
         * 所以会出现，再次addView时候，原有的已经移动过的位置会回复到默认值
         * 需要重新配置下layoutParams信息，将最新的位置信息更新至layoutParams中
         */
        val params: FrameLayout.LayoutParams =
            layoutParams as FrameLayout.LayoutParams
        params.leftMargin = l
        params.topMargin = t
        layoutParams = params



    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

//        setMeasuredDimension(
//            aViewWidth,//屏幕宽
//            aViewHeight
//        )
    }

    /**
     * 以下两个方法设置View居中画布显示
     * 执行顺序（1）onMeasure（2）onSizeChanged
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        aViewWidth = w
        aViewHeight = h
    }


}